package com.example.saas.handler;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.example.saas.config.properties.TenantProperties;
import com.example.saas.context.TenantContext;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.NullValue;
import org.springframework.stereotype.Component;

/**
 * 租户逻辑处理器
 */
@Slf4j
@Component
public class TenantHandler implements TenantLineHandler {

    private final TenantProperties tenantProperties;

    public TenantHandler(TenantProperties tenantProperties) {
        this.tenantProperties = tenantProperties;
    }

    /**
     * 获取租户Id
     */
    @Override
    public Expression getTenantId() {
        String tenantId = TenantContext.getTenantId();
        log.info("当前租户Id: {}", tenantId);
        return ObjUtil.isNull(tenantId) ? new NullValue() : new LongValue(tenantId);
    }

    /**
     * 获取租户字段列名
     */
    @Override
    public String getTenantIdColumn() {
        return tenantProperties.getColumn();
    }

    /**
     * 根据表名判断是否忽略拼接多租户条件
     */
    @Override
    public boolean ignoreTable(String tableName) {
        return TenantContext.getTenantSkipFlag() || CollUtil.contains(tenantProperties.getIgnoreTables(), tableName);
    }

}
